package com.hxt.xt.service.z.rule;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.assertj.core.util.Lists;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import com.google.common.base.Stopwatch;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.hxt.framework.utils.DateUtil;
import com.hxt.framework.utils.UuidUtils;
import com.hxt.util.CollectionUtil;
import com.hxt.util.ExcelTool;
import com.hxt.util.MinioClientUtils;
import com.hxt.util.POIUtil;
import com.hxt.util.StringUtil;
import com.hxt.util.TypeConvert;
import com.hxt.xt.model.TDealer;
import com.hxt.xt.model.TDealerOutRecord;
import com.hxt.xt.model.TImportRecord;
import com.hxt.xt.model.TInvoice;
import com.hxt.xt.model.TInvoiceFile;
import com.hxt.xt.model.TProduct;
import com.hxt.xt.model.TToken;
import com.hxt.xt.model.TXlsxModel;
import com.hxt.xt.service.base.BaseMgr;
import com.hxt.xt.service.z.bean.SP;

import ch.qos.logback.core.joran.util.beans.BeanUtil;

@Component("com.hxt.xt.service.z.rule.CommonRule")
public class CommonRule extends BaseMgr {

	/**
	 * 1.登录，成功返回代理商
	 */
	public Map<String, Object> login(String name, String pwd) throws Exception {
		Map<String, Object> m = Maps.newHashMap();

		List<Integer> flag = rule.iMyBatisDao.query("CommonCustomMapper.isExsit",
				ImmutableMap.of("name", name, "pwd", pwd));
		if (BooleanUtils.negate(ObjectUtils.isEmpty(flag)) && flag.get(0).intValue() > 0) {
			// 返回代理商信息

			m.put("token", getToken(flag.get(0).intValue()));

			m.put("sheets", getMySheet());

			return m;
		}

		return null;
	}

	/**
	 * 获取模板列表
	 */
	public List<Map<String, Object>> getMySheet() throws Exception {

		return rule.iMyBatisDao.query("CommonCustomMapper.getMySheet", null);
	}

	/**
	 * 成功登录后返回token
	 * 
	 * @param userid
	 * @return
	 */
	public String getToken(Integer userid) throws Exception {
		String token = "";
		TToken tk = new TToken();
		tk.setUserid(userid);
		token = StringUtil.getUUID();

		tk = rule.tokenDao.getObjectByModel(tk);
		// 数据库中不存在
		if (tk == null) {
			tk = new TToken();
			tk.setUserid(userid);
			tk.setToken(token);
			tk.setCreate_time(DateUtil.getToday());
			rule.tokenDao.saveObject(tk);
		} else {
			tk.setToken(token);

			rule.tokenDao.deleteObjectById(tk.getId());
			tk = new TToken();
			tk.setUserid(userid);
			tk.setToken(token);
			tk.setCreate_time(DateUtil.getToday());
			rule.tokenDao.saveObject(tk);

		}

		return token;

	}

	/**
	 * 成功登录后返回经销商
	 * 
	 * @param userid
	 * @return
	 */
	public List<Map<String, Object>> getDealers(String name, String province, String city) throws Exception {

		return rule.iMyBatisDao.query("CommonCustomMapper.allDealers",
				ImmutableMap.of("name", name, "province", province, "city", city));
	}

	/**
	 * 
	 * 返回省
	 * 
	 * @param
	 * @return
	 */
	public List<Map<String, Object>> getProvince() throws Exception {

		return rule.iMyBatisDao.query("CommonCustomMapper.getProvince", null);
	}

	/**
	 * 
	 * 返回市
	 * 
	 * @param
	 * @return
	 */
	public List<Map<String, Object>> getCity(String pid) throws Exception {

		return rule.iMyBatisDao.query("CommonCustomMapper.getCity", ImmutableMap.of("pid", pid));
	}

	/**
	 * 
	 * 根据用户token返回用户信息
	 * 
	 * @param
	 * @return
	 */
	public List<Map<String, Object>> getUserByToken(String token) throws Exception {

		return rule.iMyBatisDao.query("CommonCustomMapper.getUserByToken", ImmutableMap.of("token", token));
	}

	/**
	 * 
	 * 导入t_product（产品）， 导入t_my_storage（我的库存）, 导入t_import_record（导入记录表）
	 * 导入t_storage_record(总记录表)
	 * 
	 * @param
	 * @return
	 */
	public void importAll(String xmlTemple, String key, Integer curTime, int limitCnt) throws Exception {

		List<TProduct> proList = importProduct(xmlTemple, key, curTime, limitCnt);
		if (proList != null && proList.size() > 0) {
			importStorage(proList, curTime, limitCnt);

			List<Map<String, Object>> lt = rule.iMyBatisDao.query("CommonCustomMapper.getPriceNum",
					ImmutableMap.of("curTime", curTime));

			importRecord(key, TypeConvert.strToint(lt.get(0).get("buynum").toString()),
					new BigDecimal(lt.get(0).get("totalprice").toString()), curTime, proList.size());

			importStorageRecord(proList, curTime, limitCnt);

		}

	}

	private void importStorageRecord(List<TProduct> list, Integer curTime, int limitCnt) {
		// TODO Auto-generated method stub

		Stopwatch sw = Stopwatch.createStarted();

		// 分批处理
		if (null != list && list.size() > 0) {
			int pointsDataLimit = limitCnt;// 限制条数
			Integer size = list.size();
			// 判断是否有必要分批
			if (pointsDataLimit < size) {
				int part = size / pointsDataLimit;// 分批数
				System.out.println("共有 ： " + size + "条，！" + " 分为 ：" + part + "批");
				//
				for (int i = 0; i < part; i++) {
					// 1000条
					List<TProduct> listPage = list.subList(0, pointsDataLimit);
					rule.iMyBatisDao.insert("CommonCustomMapper.importStorageRecord", listPage);
					// 剔除
					list.subList(0, pointsDataLimit).clear();
				}

				if (!list.isEmpty()) {
					rule.iMyBatisDao.insert("CommonCustomMapper.importStorageRecord", list);
				}
			} else {
				rule.iMyBatisDao.insert("CommonCustomMapper.importStorageRecord", list);
			}
		} else {
			System.out.println("没有数据!!!");
		}

		System.out.println("导入库存执行时间:" + sw.toString());

	}

	/**
	 * 
	 * 导入t_import_record id cnt money key create_time orgid
	 * 
	 * @param
	 * @return
	 */
	public void importRecord(String key, int cnt, BigDecimal money, Integer curTime, int size) {

		rule.impRecordDao.saveObject(new TImportRecord(cnt, money, key, curTime, 1, size));

	}

	/**
	 * 
	 * 批量导入产品
	 * 
	 * @param
	 * @return
	 */
	public List<TProduct> importProduct(String xmlTemple, String key, Integer curTime, int limitCnt) throws Exception {
		TXlsxModel txm = rule.tXlsxModelDao.getObjectById(TypeConvert.strToint(xmlTemple));
		String content = txm.getMc();

		List<String[]> listXMLS = POIUtil.readExcel(key, content);
//
//		List<ProdcutBean> beans = TypeConvert.strToProductBean(list);

		List<TProduct> list = Lists.newArrayList();
		List<TProduct> srcList = Lists.newArrayList();
		for (int i = 0; i < listXMLS.size(); i++) {
			TProduct tp = new TProduct(listXMLS.get(i)[0], listXMLS.get(i)[1], listXMLS.get(i)[2], listXMLS.get(i)[3],
					listXMLS.get(i)[4], listXMLS.get(i)[5], new BigDecimal(listXMLS.get(i)[10]),
					new Integer(listXMLS.get(i)[12]),
					new BigDecimal(listXMLS.get(i)[10]).multiply(new BigDecimal(listXMLS.get(i)[12])),
					listXMLS.get(i)[6], listXMLS.get(i)[7], listXMLS.get(i)[8], listXMLS.get(i)[9], listXMLS.get(i)[11],
					listXMLS.get(i)[13], StringUtil.getUUID(), curTime);
			list.add(tp);

		}

		srcList = CollectionUtil.deepCopy(list);

		Stopwatch sw = Stopwatch.createStarted();

		// 分批处理
		if (null != list && list.size() > 0) {
			int pointsDataLimit = limitCnt;// 限制条数
			Integer size = list.size();
			// 判断是否有必要分批
			if (pointsDataLimit < size) {
				int part = size / pointsDataLimit;// 分批数
				System.out.println("共有 ： " + size + "条，！" + " 分为 ：" + part + "批");
				//
				for (int i = 0; i < part; i++) {
					// 1000条
					List<TProduct> listPage = list.subList(0, pointsDataLimit);
					rule.iMyBatisDao.insert("CommonCustomMapper.importProduct", listPage);
					// 剔除
					list.subList(0, pointsDataLimit).clear();
				}

				if (!list.isEmpty()) {
					rule.iMyBatisDao.insert("CommonCustomMapper.importProduct", list);
				}
			} else {
				rule.iMyBatisDao.insert("CommonCustomMapper.importProduct", list);
			}
		} else {
			System.out.println("没有数据!!!");
		}

		System.out.println("导入产品执行时间:" + sw.toString());

		return srcList;
	}

	/**
	 * 
	 * 批量导入t_my_storage
	 * 
	 * @param
	 * @return
	 */
	public void importStorage(List<TProduct> list, Integer curTime, int limitCnt) throws Exception {

		Stopwatch sw = Stopwatch.createStarted();

		// 分批处理
		if (null != list && list.size() > 0) {
			int pointsDataLimit = limitCnt;// 限制条数
			Integer size = list.size();
			// 判断是否有必要分批
			if (pointsDataLimit < size) {
				int part = size / pointsDataLimit;// 分批数
				System.out.println("共有 ： " + size + "条，！" + " 分为 ：" + part + "批");
				//
				for (int i = 0; i < part; i++) {
					// 1000条
					List<TProduct> listPage = list.subList(0, pointsDataLimit);
					rule.iMyBatisDao.insert("CommonCustomMapper.importStorage", listPage);
					// 剔除
					list.subList(0, pointsDataLimit).clear();
				}

				if (!list.isEmpty()) {
					rule.iMyBatisDao.insert("CommonCustomMapper.importStorage", list);
				}
			} else {
				if (list != null && list.size() > 0) {
					List<TProduct> tpListSub = Lists.newArrayList();
					List<TProduct> tpList = Lists.newArrayList();
					for (int p = 0; p < list.size(); p++) {
						int buyNum = list.get(p).getBuynum().intValue();
						// 拆开记录
						if (buyNum > 1) {

							for (int y = 0; y < buyNum; y++) {
								TProduct tp = new TProduct();

								BeanUtils.copyProperties(tp, list.get(p));
								tp.setBuynum(1);
								tpList.add(tp);
							}
							tpListSub.add(list.get(p));
						}

					}
					list.removeAll(tpListSub);
					list.addAll(tpList);
				}
				rule.iMyBatisDao.insert("CommonCustomMapper.importStorage", list);
			}
		} else {
			System.out.println("没有数据!!!");
		}

		System.out.println("导入库存执行时间:" + sw.toString());

	}

	/**
	 * 添加代理商
	 * 
	 * @param
	 * @return
	 */
	public void addDealer(TDealer dealer) throws Exception {

		rule.dealerDao.saveObject(dealer);

	}

	/**
	 * 根据用户传的key，返回路径
	 * 
	 * @param
	 * @return
	 */
	public String presignedURL(String key) throws Exception {

		return MinioClientUtils.presignedURL(key);

	}

	/**
	 * 根据用户传的key，返回表头
	 * 
	 * @param
	 * @return
	 */
	public List<String> getSheetColumn(String key) throws Exception {
		List<String> list = Lists.newArrayList();
		InputStream inp = MinioClientUtils.getObjectToInputStream(key);
//		String filePath = "D://tools//Data//zbak//d1amrCWa0U7e15pNUlNEYvKcFLLern8Z.xlsx";
//		FileInputStream inp = new FileInputStream(filePath); 
		Workbook wb = new XSSFWorkbook(inp);
		Sheet sheet = wb.getSheetAt(0); // 获得第三个工作薄(2008工作薄)
		// 填充上面的表格,数据需要从数据库查询
		Row row0 = sheet.getRow(0); // 获得工作薄的第五行
		// 获得总列数
		int coloumNum = sheet.getRow(0).getPhysicalNumberOfCells();

		for (int i = 0; i < coloumNum; i++) {
			list.add(ExcelTool.excelColIndexToStr(i + 1) + ":" + row0.getCell(i));
		}
		return list;

	}

	/**
	 * 获取产品名称
	 * 
	 * @param
	 * @return
	 */
	public List<Map<String, Object>> getProductName() throws Exception {

		return rule.iMyBatisDao.query("CommonCustomMapper.getProductName", null);

	}

	/**
	 * 获取产品规格
	 * 
	 * @param
	 * @return
	 */
	public List<Map<String, Object>> getModel(String name) throws Exception {

		return rule.iMyBatisDao.query("CommonCustomMapper.getModel", ImmutableMap.of("name", name));

	}

	/**
	 * 
	 * @param
	 * @return
	 */
	@SuppressWarnings("unused")
	public void com19999() throws Exception {
//		Iterable<ProdcutBeanH2> iter = rule.productRepository.findAll();

		System.out.println("com19999");

	}

	/**
	 * 获取入库单列表
	 * 
	 * @param
	 * @return
	 */
	public List<Map<String, Object>> getImportXlsInfo(String beginTime, String endTime) throws Exception {
		List<Map<String, Object>> list2 = Lists.newArrayList();
		int flag = 0;
		List<Map<String, Object>> list = rule.iMyBatisDao.query("CommonCustomMapper.getImportXlsInfo",
				ImmutableMap.of("beginTime", beginTime, "endTime", endTime));
		if (BooleanUtils.negate(ObjectUtils.isEmpty(list))) {
			for (int i = 0; i < list.size(); i++) {
				int cmpCnt = TypeConvert.strToint(list.get(i).get("impCnt").toString());
				int create_time = TypeConvert.strToint(list.get(i).get("create_time").toString());
				// 如果入库的记录数量（excel行数）与管理员的库存数量不对，则表示有产品已出过库
				List<Integer> cnt = rule.iMyBatisDao.query("CommonCustomMapper.isNumInit",
						ImmutableMap.of("create_time", create_time));
				if (cnt.get(0).intValue() != cmpCnt) {
					continue;
				}
//				List<Map<String, Object>> isPingList = rule.iMyBatisDao.query("CommonCustomMapper.siPing",
//						ImmutableMap.of("create_time", create_time));
//				if (BooleanUtils.negate(ObjectUtils.isEmpty(isPingList))) {
//					for (int x = 0; x < isPingList.size(); x++) {
//						String puuid = isPingList.get(x).get("puuid").toString();
//
//						List<Integer> byCnt = rule.iMyBatisDao.query("CommonCustomMapper.isBuyed",
//								ImmutableMap.of("puuid", puuid));
//						if (byCnt.get(0).intValue() != 0) {
//							flag = 1;
//							break;
//						}
//
//					}
//				}
				if (flag == 0) {
					list.get(i).put("singKey", MinioClientUtils.presignedURL(list.get(i).get("key").toString()));
					list.get(i).remove("impCnt");
					list2.add(list.get(i));
				}

			}

		}
		return list2;

	}

	/**
	 * 获取管理员入库列表
	 * 
	 * @param
	 * @return
	 */
	public Map<String, Object> getStorageList(String name, String model, String regName, String batchNum)
			throws Exception {

		Map<String, Object> ret = Maps.newHashMap();
		List<Map<String, Object>> list = rule.iMyBatisDao.query("CommonCustomMapper.getStorageList",
				ImmutableMap.of("name", name, "model", model, "regName", regName, "batchNum", batchNum));

		List<Integer> cnt = rule.iMyBatisDao.query("CommonCustomMapper.getTotalBuy",
				ImmutableMap.of("name", name, "model", model, "regName", regName, "batchNum", batchNum));

		ret.put("list", list);
		ret.put("sum", cnt.get(0));

		return ret;

	}

	/**
	 * 获取移库时管理员 --库存列表
	 * 
	 * @param
	 * @return
	 */
	public List<Map<String, Object>> getStorageListByType(String name, String model, String regName, String batchNum)
			throws Exception {

		return rule.iMyBatisDao.query("CommonCustomMapper.getStorageListByType",
				ImmutableMap.of("name", name, "model", model, "regName", regName, "batchNum", batchNum));

	}

	/**
	 * 获取入库列表
	 * 
	 * @param
	 * @return
	 */
	public List<Map<String, Object>> getStorageDetail(String model) throws Exception {
		List<Map<String, Object>> list = rule.iMyBatisDao.query("CommonCustomMapper.getStorageDetail",
				ImmutableMap.of("model", model));

		if (BooleanUtils.negate(ObjectUtils.isEmpty(list))) {
			for (int i = 0; i < list.size(); i++) {
				String batchnum = list.get(i).get("batchnum").toString();
				List<Integer> cnt = rule.iMyBatisDao.query("CommonCustomMapper.isTwoImp",
						ImmutableMap.of("batchnum", StringUtils.trim(batchnum)));
				list.get(i).put("isTwoImp", cnt.get(0));
				list.get(i).put("record", Lists.newArrayList());
				if (cnt.get(0).intValue() > 1) {
					list.get(i).put("record",
							rule.iMyBatisDao.query("CommonCustomMapper.record", ImmutableMap.of("batchnum", batchnum)));
				}

			}
		}

		return list;

	}

	/**
	 * 获取用户操作记录
	 * 
	 * @param
	 * @return
	 */
	public List<Map<String, Object>> getOperRecord() throws Exception {
		return rule.iMyBatisDao.query("CommonCustomMapper.getOperRecord", null);
	}

	/**
	 * 获取用户异常记录
	 * 
	 * @param
	 * @return
	 */
	public List<Map<String, Object>> getExcepRecord() throws Exception {
		return rule.iMyBatisDao.query("CommonCustomMapper.getExcepRecord", null);
	}

	/**
	 * 逻辑删除代理商
	 * 
	 * @param
	 * @return
	 */
	public void delDealer(String id) throws Exception {
		rule.iMyBatisDao.update("CommonCustomMapper.delDealer", ImmutableMap.of("id", id));
	}

	/**
	 * 返回备货代理商-type=2
	 * 
	 * @param
	 * @return
	 */
	public List<Map<String, Object>> searchDealer(String type) throws Exception {
		return rule.iMyBatisDao.query("CommonCustomMapper.searchDealer", ImmutableMap.of("type", type));
	}

	/**
	 * 编辑代理商
	 * 
	 * @param
	 * @return
	 */
	public void editDealer(TDealer dealer) throws Exception {
		rule.dealerDao.updateObjectById(dealer);
	}

	/**
	 * 
	 * 
	 * @param
	 * @return
	 */
	public Map<String, Object> InvoiceInfo(String dealerId, String beginTime, String endTime) throws Exception {

		Map<String, Object> m = Maps.newHashMap();
		m.put("list", getInvoiceList(dealerId, beginTime, endTime));
		m.put("totalMoney", getInvoiceMoney(dealerId, beginTime, endTime).get(0).get("money"));
		return m;
	}

	/**
	 * 开票列表
	 * 
	 * @param
	 * @return
	 */
	public List<Map<String, Object>> getInvoiceList(String dealerId, String beginTime, String endTime)
			throws Exception {

		List<Map<String, Object>> list = rule.iMyBatisDao.query("CommonCustomMapper.getInvoiceList",
				ImmutableMap.of("dealerId", dealerId, "beginTime", beginTime, "endTime", endTime));
		if (BooleanUtils.negate(ObjectUtils.isEmpty(list))) {
			for (int i = 0; i < list.size(); i++) {
				String id = list.get(i).get("id").toString();
				list.get(i).put("list", Lists.newArrayList());
				List<Map<String, Object>> fileList = rule.iMyBatisDao.query("CommonCustomMapper.getInvoiceListFile",
						ImmutableMap.of("tid", id));

				if (BooleanUtils.negate(ObjectUtils.isEmpty(fileList))) {
					for (int x = 0; x < fileList.size(); x++) {

						fileList.get(x).put("keyFile",
								MinioClientUtils.presignedURL(fileList.get(x).get("key").toString()));
					}

				}
				list.get(i).put("list", fileList);

			}
		}
		return list;
	}

	/**
	 * 开票总金额
	 * 
	 * @param
	 * @return
	 */
	public List<Map<String, Object>> getInvoiceMoney(String dealerId, String beginTime, String endTime)
			throws Exception {
		return rule.iMyBatisDao.query("CommonCustomMapper.getInvoiceTotalMoney",
				ImmutableMap.of("dealerId", dealerId, "beginTime", beginTime, "endTime", endTime));
	}

	/**
	 * 开票
	 * 
	 * @param
	 * @return
	 */
	public void makeInvoice(String dealerId, String dealerName, String money, List<String> files) throws Exception {
		int createTime = DateUtil.getToday();
		TInvoice ivo = new TInvoice();

		ivo.setCreatetime(createTime);
		ivo.setDealer_id(TypeConvert.strToint(dealerId));
		ivo.setDealer_name(dealerName);
		ivo.setIsdel(0);
		ivo.setMoney(new BigDecimal(money));
		rule.tInvoiceDao.saveObject(ivo);

		// 保存文件
		for (int i = 0; i < files.size(); i++) {
			TInvoiceFile file = new TInvoiceFile();
			file.setCreatetime(createTime);
			file.setIsdel(0);
			file.setKey(files.get(i));
			file.setTid(ivo.getId());
			rule.tInvoiceFileDao.saveObject(file);
		}
	}

	/**
	 * 编辑开票
	 * 
	 * @param
	 * @return
	 */
	public void editInvoice(String id, String dealerId, String dealerName, List<String> files, String money)
			throws Exception {
		int createTime = DateUtil.getToday();
		TInvoice ivo = rule.tInvoiceDao.getObjectById(TypeConvert.strToint(id));
		if (BooleanUtils.negate(ObjectUtils.isEmpty(ivo))) {
			ivo.setDealer_id(TypeConvert.strToint(dealerId));
			ivo.setDealer_name(dealerName);
			ivo.setMoney(new BigDecimal(money));
			ivo.setCreatetime(createTime);
			rule.tInvoiceDao.updateObjectById(ivo);
		}

		List<Map<String, Object>> ilf = rule.iMyBatisDao.query("CommonCustomMapper.getInvoiceListFile",
				ImmutableMap.of("tid", id));
		if (BooleanUtils.negate(ObjectUtils.isEmpty(ilf))) {
			for (int x = 0; x < ilf.size(); x++) {
				TInvoiceFile tf = new TInvoiceFile();
				tf.setId(TypeConvert.strToint(ilf.get(x).get("id").toString()));
				tf.setIsdel(1);
				rule.tInvoiceFileDao.updateObjectById(tf);
			}
		}

		// 保存文件
		for (int i = 0; i < files.size(); i++) {
			TInvoiceFile file = new TInvoiceFile();
			file.setCreatetime(createTime);
			file.setIsdel(0);
			file.setKey(files.get(i));
			file.setTid(ivo.getId());
			file.setCreatetime(createTime);
			rule.tInvoiceFileDao.saveObject(file);
		}

	}

	/**
	 * 返回二级库列表
	 * 
	 * @param
	 * @return
	 */
	public List<Map<String, Object>> dOutStorageList(String dealerId, String name, String model, String batchnum,
			String type) throws Exception {
		return rule.iMyBatisDao.query("CommonCustomMapper.dOutStorageList", ImmutableMap.of("dealerId", dealerId,
				"name", name, "model", model, "batchnum", batchnum, "type", type));
	}

	/**
	 * 二级库出库
	 * 
	 * @param
	 * @return
	 */
	public void dOutStorage(Integer did, String dname, String totalSalePrice, String cnt, List<SP> list)
			throws Exception {
		Integer curTime = DateUtil.getToday();
		String uuid = UuidUtils.getUUid();

		if (list != null && list.size() > 0) {
			rule.iMyBatisDao.update("CommonCustomMapper.dOutStorage",
					ImmutableMap.of("list", list, "uuid", uuid, "curTime", curTime));
		}

		TDealerOutRecord tor = new TDealerOutRecord(did, dname, TypeConvert.strToint(cnt),
				new BigDecimal(totalSalePrice), curTime, 1, uuid);

		rule.tDealerOutRecordDao.saveObject(tor);
	}

	/**
	 * 保存xls模板
	 * 
	 * @param
	 * @return
	 */
	public void saveXlsTemple(String mc, String descd) throws Exception {

		TXlsxModel tm = new TXlsxModel();
		tm.setCreatetime(DateUtil.getToday());
		tm.setDescd(descd);
		tm.setIsdel(0);
		tm.setMc(mc);
		rule.tXlsxModelDao.saveObject(tm);

	}

	/**
	 * 模板列表
	 */
	public List<Map<String, Object>> xlsTempleList() throws Exception {
		return rule.iMyBatisDao.query("CommonCustomMapper.xlsTempleList", null);
	}

	/**
	 * 删除模板
	 */
	public void delXlsTemple(List<String> ids) throws Exception {
		if (ids != null && ids.size() > 0) {
			rule.iMyBatisDao.update("CommonCustomMapper.delXlsTemple", ids);
		}
	}

	/**
	 * 
	 * 产品出库 type为1是从导入模板出库，2是库里查询勾选出库
	 * 
	 */
	public void outStorage(int type, String create_time, String did, String dname, String scale, String saleMoney,
			String cnt, String money) throws Exception {
		int curTime = DateUtil.getToday();
		// 这个接口只负责普通经销商的出库

		if (type == 1) {

			// 1.t_my_storage减少
			List<Map<String, Object>> list = rule.iMyBatisDao.query("CommonCustomMapper.reduceKcList",
					ImmutableMap.of("create_time", create_time));
			if (BooleanUtils.negate(ObjectUtils.isEmpty(list))) {
				rule.iMyBatisDao.delete("CommonCustomMapper.delStorage", list);
				// 2.t_dealer_storage增加

				for (int i = 0; i < list.size(); i++) {
					list.get(i).put("did", did);
					list.get(i).put("create_time", curTime);
					list.get(i).put("dname", dname);
					list.get(i).put("scale", scale);
					list.get(i).put("tSaleMoney", saleMoney);

				}
				rule.iMyBatisDao.insert("CommonCustomMapper.addDealerStorage", list);

//			3.t_admin_out_record
				Map<String, Object> p = Maps.newHashMap();
				p.put("did", did);
				p.put("dname", dname);
				p.put("cnt", cnt);
				p.put("money", money);
				p.put("create_time", curTime);
				p.put("scale", scale);
				p.put("tSaleMoney", saleMoney);

				rule.iMyBatisDao.insert("CommonCustomMapper.insertAdminOutRecord", p);

//				4.t_storage_record
				rule.iMyBatisDao.insert("CommonCustomMapper.addStorageRecordAdminOut", list);

			}
			System.out.println("");
		}
	}

	/**
	 * 获取所有入库单列表
	 * 
	 * @param
	 * @return
	 */
	public List<Map<String, Object>> impStorageListAdmin(String beginTime, String endTime) throws Exception {
		List<Map<String, Object>> list = rule.iMyBatisDao.query("CommonCustomMapper.getImportXlsInfo",
				ImmutableMap.of("beginTime", beginTime, "endTime", endTime));
		if (BooleanUtils.negate(ObjectUtils.isEmpty(list))) {
			for (int i = 0; i < list.size(); i++) {
				list.get(i).put("singKey", MinioClientUtils.presignedURL(list.get(i).get("key").toString()));
				list.get(i).remove("impCnt");

			}

		}
		return list;

	}

	/**
	 * 批发时查看-入库存记录-详细
	 * 
	 * @param
	 * @return
	 */
	public Map<String, Object> impStorageListDetail(String create_time) throws Exception {

		Map<String, Object> p = Maps.newHashMap();
		p.put("list", rule.iMyBatisDao.query("CommonCustomMapper.impStorageListDetail",
				ImmutableMap.of("create_time", create_time)));

		List<Map<String, Object>> list = rule.iMyBatisDao.query("CommonCustomMapper.impStorageListDetailSumMoney",
				ImmutableMap.of("create_time", create_time));
		if (BooleanUtils.negate(ObjectUtils.isEmpty(list)) && null != list.get(0)) {
			p.put("sumBuyNum", list.get(0).get("sumBuyNum"));
			p.put("sumByPrice", list.get(0).get("sumByPrice"));
		}

		return p;

	}

	/**
	 * 获取待出库--入库列表
	 * 
	 * @param
	 * @return
	 */
	public List<Map<String, Object>> getDOutStorageList(String name, String model, String batchNum) throws Exception {

		return rule.iMyBatisDao.query("CommonCustomMapper.getDOutStorageList",
				ImmutableMap.of("name", name, "model", model, "batchNum", batchNum));

	}

}
